package settings;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.imstlife.vending.R;
import com.imstlife.vending.activity.MyApplication;
import com.imstlife.vending.activity.SplashActivity;
import com.imstlife.vending.api.MarvAPI;
import com.imstlife.vending.plus.TmpHelper;
import com.imstlife.vending.utils.AppUtil;
import com.imstlife.vending.utils.Cof;
import com.imstlife.vending.utils.DialogUtil;
import com.imstlife.vending.utils.DownLoadTask;
import com.imstlife.vending.utils.RootShellCmd;
import com.imstlife.vending.utils.SharePersistentUtil;
import com.imstlife.vending.utils.T;
import com.imstlife.vending.vo.CheckUpdateRespone;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 更多设置
 */
public class MoreSettingsFragment extends Fragment {

    private LinearLayout backButtonLayout;

    private TextView clearCache, cacheSize;
    private TextView update;
    private TextView factoryMode;

    private TextView suggestion;

    // 当前版本的包名
    private String packageNames;
    // 缓存大小
    private String sizeString;

    private TextView tvTest;

    private Spinner spinnerSerial;

    //温度控制开关
    private Switch tmpSwitch;

    //当前温度
    private TextView tvCurrentTmp;

    private TextView tvSetTmp;
    /**
     * 温度控制操作栏 默认隐藏
     */
    private RelativeLayout rlTmp;

    /**
     * 设置温度加减
     */
    private Button btnTmpAdd, btnTmpReduce;

    /**
     * 制冷 加热切换
     */
    private RadioGroup radioGroup;

    /**
     * LED灯条开关
     */
    private Switch switchLed;


    /**
     * 玻璃加热
     */
    private Switch switchHeatGlass;


    private TmpHelper tmpHelper;
    private TextView updateSp;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootLayout = inflater.inflate(R.layout.fragment_more_settings,
                container, false);

        cacheSize = (TextView) rootLayout
                .findViewById(R.id.fragment_more_setting_cache_size);


        // 温控升级--------view

        tmpSwitch = (Switch) rootLayout.findViewById(R.id.switch_fg_more_setting_tmp);
        tvCurrentTmp = (TextView) rootLayout.findViewById(R.id.tv_fg_more_setting_tme_current_value);
        rlTmp = (RelativeLayout) rootLayout.findViewById(R.id.rl_fg_more_setting_set_tmp);
        btnTmpAdd = (Button) rootLayout.findViewById(R.id.btn_fg_more_setting_add);
        btnTmpReduce = (Button) rootLayout.findViewById(R.id.btn_fg_more_setting_reduce);
        radioGroup = (RadioGroup) rootLayout.findViewById(R.id.rg_fg_more_setting_mode);
        switchLed = (Switch) rootLayout.findViewById(R.id.switch_fg_more_setting_led);
        switchHeatGlass = (Switch) rootLayout.findViewById(R.id.switch_fg_more_setting_heat_glass);
        tvSetTmp = (TextView) rootLayout.findViewById(R.id.tv_fg_more_setting_tem_set_value);

        tmpHelper = new TmpHelper(getContext(), tmpSwitch, tvCurrentTmp, rlTmp, btnTmpAdd, btnTmpReduce, radioGroup, switchLed, switchHeatGlass, tvSetTmp);
        //温控升级-------view


        spinnerSerial = (Spinner) rootLayout.findViewById(R.id.spiner_fg_more_setting_serial);
        List<String> sps = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            sps.add("串口" + i);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, sps);
        spinnerSerial.setAdapter(adapter);

        spinnerSerial.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                SharePersistentUtil.saveSharePersistent(getActivity(), "marvsmart", "serial", position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tvTest = (TextView) rootLayout.findViewById(R.id.tv_fg_more_test);
        tvTest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        update = (TextView) rootLayout
                .findViewById(R.id.fragment_more_setting_update);
        update.setOnClickListener(new ButtonListener());

        TextView updateAdmin = (TextView) rootLayout.findViewById(R.id.fragment_more_admin_update);
        updateAdmin.setOnClickListener(new ButtonListener());

        updateSp = (TextView) rootLayout.findViewById(R.id.fragment_more_update_sp);
        updateSp.setOnClickListener(new ButtonListener());
        updateSp.setText("修改串口（当前串口"+SharePersistentUtil.getSharePersistentString(getActivity(),"spnum")+"）");

        TextView appReboot = (TextView) rootLayout.findViewById(R.id.fragment_more_app_reboot);
        appReboot.setOnClickListener(new ButtonListener());

        TextView deviceReboot = (TextView) rootLayout.findViewById(R.id.fragment_more_device_reboot);
        deviceReboot.setOnClickListener(new ButtonListener());

        factoryMode = (TextView) rootLayout
                .findViewById(R.id.fragment_more_setting_factory_mode);
        factoryMode.setOnClickListener(new ButtonListener());

        suggestion = (TextView) rootLayout
                .findViewById(R.id.fragment_more_setting_suggestion);
        suggestion.setOnClickListener(new ButtonListener());

        PackageInfo info;
        try {
            info = getActivity().getPackageManager().getPackageInfo(
                    getActivity().getPackageName(), 0);
            // 当前应用的版本名称
            // versionName = info.versionName;
            // 当前版本的版本号
            // int versionCode = info.versionCode;
            // 当前版本的包名
            packageNames = info.packageName;

        } catch (Exception e) {
            e.printStackTrace();
        }


        return rootLayout;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (tmpHelper != null) {
            tmpHelper.ref();
        }
        spinnerSerial.setSelection(SharePersistentUtil.getSharePersistentInt(getActivity(), "marvsmart", "serial"));
    }

    DialogUtil dialogUtil = new DialogUtil();

    public void psw_updata(final String psw, final String key) {
        dialogUtil.plantdialog(getContext(), new DialogUtil.more_plantdialog() {
            @Override
            public void ok_check(String str) {
                //获取是否有修改过的密码
                String judge = SharePersistentUtil.getSharePersistentString(getActivity(), key);
                String adminPassword = SharePersistentUtil.getSharePersistentString(getActivity(), "adminPassword");
                if (judge.equals("") || judge == null) {
                    if (str.equals("") || str == null) {
                        T.showShort2(getActivity(), "密码不能为空");
                    } else if (str.equals(psw) || str.equals(adminPassword)) {
                        dialogUtil.plantdialog(getActivity(), new DialogUtil.more_plantdialog() {
                            @Override
                            public void ok_check(String str) {
                                //保存修改过的密码
                                SharePersistentUtil.saveSharePersistent(getActivity(), key, str);
                            }
                        }, 2, null);
                    } else {
                        T.showShort2(getActivity(), "密码错误");
                    }
                } else {
                    if (str.equals("") || str == null) {
                        T.showShort2(getActivity(), "密码不能为空");
                    } else if (str.equals(judge) || str.equals(adminPassword)) {
                        dialogUtil.plantdialog(getActivity(), new DialogUtil.more_plantdialog() {
                            @Override
                            public void ok_check(String str) {
                                //保存修改过的密码
                                SharePersistentUtil.saveSharePersistent(getActivity(), key, str);
                            }
                        }, 2, null);
                    } else {
                        T.showShort2(getActivity(), "密码错误");
                    }
                }
            }
        }, 1, null);
    }

    private AlertDialog dialog;

    private class ButtonListener implements OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.fragment_more_app_reboot:
                    Intent intent = new Intent(MyApplication.getInstance(), SplashActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    MyApplication.getInstance().startActivity(intent);
                    android.os.Process.killProcess(android.os.Process.myPid());
                    break;
                case R.id.fragment_more_device_reboot:
                    if (android.os.Build.VERSION.SDK_INT > 19) {
                        try {
                            Runtime.getRuntime().exec("su");
                            Runtime.getRuntime().exec("reboot");
                        } catch (IOException e) {
                        }
                    } else {
                        try {
                            Process process = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot "});  //重启
                            process.waitFor();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case R.id.fragment_more_update_sp:
                    final EditText et = new EditText(getActivity());
                    // 数字键盘
                    et.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                    new AlertDialog.Builder(getActivity())
                            .setTitle(
                                    getResources()
                                            .getString(R.string.pls_input_sercode))
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setView(et)
                            .setPositiveButton(
                                    getResources().getString(R.string.sure),
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            String inputStr = et.getText()
                                                    .toString();
                                            if (inputStr.equals("1")||inputStr.equals("2")||inputStr.equals("0")){
                                                SharePersistentUtil.saveSharePersistent(getActivity(),"spnum",inputStr);
                                                updateSp.setText("修改串口（当前串口"+inputStr+"）");
                                            }else{
                                                T.showShort2(getActivity(),"序号只可以是0、1、2");
                                            }
                                        }
                                    })
                            .setNegativeButton(
                                    getResources().getString(R.string.cancle), null)
                            .show();
                    break;
                case R.id.fragment_more_admin_update:

//                    psw_updata(Cof.ADMINPWD, Cof.adminpwd);
                    final String psw = Cof.ADMINPWD;
                    final String key = Cof.adminpwd;
                    final EditText editText2 = new EditText(getActivity());
                    // 数字键盘
                    editText2.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                    new AlertDialog.Builder(getActivity())
                            .setTitle(getResources().getString(R.string.pls_input_oldadminpwd))
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setView(editText2)
                            .setPositiveButton(getResources().getString(R.string.sure),
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            String str = editText2.getText().toString();
                                            String judge = SharePersistentUtil.getSharePersistentString(getActivity(), key);
                                            String adminPassword = SharePersistentUtil.getSharePersistentString(getActivity(), "adminPassword");
                                            if (judge.equals("") || judge == null) {
                                                if (str.equals("") || str == null) {
                                                    T.showShort2(getActivity(), "密码不能为空");
                                                } else if (str.equals(psw) || str.equals(adminPassword)) {
                                                    final EditText editText3 = new EditText(getActivity());
                                                    // 数字键盘
                                                    editText3.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                                                    new AlertDialog.Builder(getActivity())
                                                            .setTitle(getResources().getString(R.string.pls_input_newadminpwd))
                                                            .setIcon(android.R.drawable.ic_dialog_info)
                                                            .setView(editText3)
                                                            .setPositiveButton(getResources().getString(R.string.sure),
                                                                    new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            String str = editText3.getText().toString();
                                                                            SharePersistentUtil.saveSharePersistent(getActivity(), key, str);
                                                                        }
                                                                    })
                                                            .setNegativeButton(
                                                                    getResources().getString(R.string.cancle), null)
                                                            .show();
                                                } else {
                                                    T.showShort2(getActivity(), "密码错误");
                                                }
                                            } else {
                                                if (str.equals("") || str == null) {
                                                    T.showShort2(getActivity(), "密码不能为空");
                                                } else if (str.equals(judge) || str.equals(adminPassword)) {
                                                    final EditText editText3 = new EditText(getActivity());
                                                    // 数字键盘
                                                    editText3.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                                                    new AlertDialog.Builder(getActivity())
                                                            .setTitle(getResources().getString(R.string.pls_input_newadminpwd))
                                                            .setIcon(android.R.drawable.ic_dialog_info)
                                                            .setView(editText3)
                                                            .setPositiveButton(getResources().getString(R.string.sure),
                                                                    new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            String str = editText3.getText().toString();
                                                                            SharePersistentUtil.saveSharePersistent(getActivity(), key, str);
                                                                        }
                                                                    })
                                                            .setNegativeButton(
                                                                    getResources().getString(R.string.cancle), null)
                                                            .show();
                                                } else {
                                                    T.showShort2(getActivity(), "密码错误");
                                                }
                                            }
                                        }
                                    })
                            .setNegativeButton(
                                    getResources().getString(R.string.cancle), null)
                            .show();

                    break;

                case R.id.fragment_more_setting_update:
                    checkUpdate();

                    break;
                case R.id.fragment_more_setting_suggestion:
//
                    break;

                case R.id.fragment_more_setting_factory_mode:

                    final EditText editText = new EditText(getActivity());
                    // 数字键盘
                    // editText.setInputType(EditorInfo.TYPE_CLASS_PHONE);
                    new AlertDialog.Builder(getActivity())
                            .setTitle(
                                    getResources()
                                            .getString(R.string.pls_input_pwd))
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setView(editText)
                            .setPositiveButton(
                                    getResources().getString(R.string.sure),
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            String inputStr = editText.getText()
                                                    .toString();
                                            if (inputStr.length() <= 0) {
                                                new AlertDialog.Builder(
                                                        getActivity())
                                                        .setTitle(
                                                                getResources()
                                                                        .getString(
                                                                                R.string.tishi))
                                                        .setMessage(
                                                                getResources()
                                                                        .getString(
                                                                                R.string.err_pwd))
                                                        .setPositiveButton(
                                                                getResources()
                                                                        .getString(
                                                                                R.string.sure),
                                                                null).show();
                                            } else {

                                                if (inputStr.equals("10")) {
                                                    showBackButton();
                                                    Intent intent2 = new Intent(Settings.ACTION_SETTINGS);
                                                    startActivity(intent2);

                                                } else {
                                                    new AlertDialog.Builder(
                                                            getActivity())
                                                            .setTitle(
                                                                    getResources()
                                                                            .getString(
                                                                                    R.string.tishi))
                                                            .setMessage(
                                                                    getResources()
                                                                            .getString(
                                                                                    R.string.err_pwd))
                                                            .setPositiveButton(
                                                                    getResources()
                                                                            .getString(
                                                                                    R.string.sure),
                                                                    null).show();
                                                }
                                            }
                                        }
                                    })
                            .setNegativeButton(
                                    getResources().getString(R.string.cancle), null)
                            .show();

                default:
                    break;
            }
        }
    }

    private void checkUpdate() {
        String url = Cof.Interface.URL_CHECK_UPDATE;
        String deviceId = SharePersistentUtil.getSharePersistentString(getActivity(), Cof.KEY_DEVICE_ID);
        int versionCode = AppUtil.getVersionCode(getActivity());
        String versionName = AppUtil.getVersionName(getActivity());
        MarvAPI.getInstance().checkUpdate(url, deviceId, Cof.KEY, versionName, versionCode + "", new MarvAPI.APIListener() {
            @Override
            public void onSuccess(Object data) {
                CheckUpdateRespone respone = (CheckUpdateRespone) data;

                if ("0".equals(respone.getStatus())) {
                    T.showShort(getActivity(), "发现新版本");
                    DownLoadTask task = new DownLoadTask();
                    task.execute(respone.getData().getDownLoadUrl());
                } else {
                    T.showShort(getActivity(), "当前已是最新版本");
                }
            }

            @Override
            public void onFailure(String msg) {
                T.showShort(getActivity(), "检查更新失败");
            }

            @Override
            public void onNetError(String msg) {
                T.showShort(getActivity(), "网络未连接");
            }
        });
    }

    /**
     * 窗口管理器
     */
    private WindowManager wm = null;

    // 移除下部悬浮按钮
    public void removeView() {
        if (wm != null) {
            wm.removeView(backButtonLayout);

            wm = null;
        }
    }

    /**
     * 显示返回悬浮按钮
     */
    private void showBackButton() {

        if (wm == null) {
            wm = (WindowManager) getActivity().getApplicationContext().getSystemService(
                    getActivity().WINDOW_SERVICE);
        }

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        params.type = WindowManager.LayoutParams.TYPE_PHONE;
        params.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.alpha = 80;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        // 调整悬浮窗显示的停靠位置为左侧上部
        params.gravity = Gravity.START | Gravity.TOP;

        LayoutInflater inflater = getActivity().getLayoutInflater();

        backButtonLayout = (LinearLayout) inflater.inflate(
                R.layout.layout_back_button, null);

        wm.addView(backButtonLayout, params);

        ImageView backView = (ImageView) backButtonLayout
                .findViewById(R.id.layout_view_back);
        backView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    if (wm != null && backButtonLayout != null) {
                        wm.removeViewImmediate(backButtonLayout);
                    }

                    // 返回
                    RootShellCmd rCmd = new RootShellCmd();
                    rCmd.simulateKey(4);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 计算缓存大小
     *
     * @author 大民
     */
    private class CalculateCacheTask extends AsyncTask<Void, Process, Integer> {

        // 处理后台执行的任务，在后台线程执行
        @Override
        protected Integer doInBackground(Void... params) {
            // TODO Auto-generated method stub
            // 获取缓存大小
//			File file = Environment.getExternalStorageDirectory(); // 得到SD卡路径
//			String fileName = file + "/Android/data/" + packageNames + "/cache"; // Universal
//																					// Loader
//			try {
//				long size = CommonUtils.getFileSize(new File(fileName)); // 得到缓存大小
//				if (size > 500000) {// 如果缓存大于500K则显示，否则不显示
//					sizeString = CommonUtils.FormatFileSize(size);// 转换为G、M、K单位大小
//				} else {
//					sizeString = "";
//				}
//
//				System.out.println(size);
//				return Integer.valueOf(1);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}

            return Integer.valueOf(0);
        }

        // 后台任务执行完之后被调用，在UI线程执行
        protected void onPostExecute(Integer result) {
            if (result.intValue() == 1) {
                // 刷新缓存大小显示
                cacheSize.setText(sizeString);
                return;
            }
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (tmpHelper != null) {
            tmpHelper.onDestory();
        }
    }
}
